/*
 * common.cpp
 *
 *  Created on: 2017年9月9日
 *      Author: xzl
 */

#include "common.h"
#include <stdarg.h>
#include <unordered_map>
#include "Util/logger.h"
#include "Util/onceToken.h"
#include "Util/TimeTicker.h"
#include "Network/TcpServer.h"
#include "Poller/EventPoller.h"
#include "Rtsp/UDPServer.h"
#include "Rtsp/RtspSession.h"
#include "cleaner.h"

using namespace std;
using namespace ZL::Util;
using namespace ZL::Rtsp;

static TcpServer<RtspSession>::Ptr s_pRtspSrv;


#ifdef __cplusplus
extern "C" {
#endif

//////////////////////////environment init///////////////////////////

API_EXPORT void CALLTYPE onAppStart(){
	static onceToken s_token([](){
		//Logger::Instance().add(std::make_shared<ConsoleChannel>("stdout", LTrace));
		Logger::Instance().setWriter(std::make_shared<AsyncLogWriter>());
		EventPoller::Instance(true);

		cleaner::Instance().push_back([](){
			s_pRtspSrv.reset();
			WorkThreadPool::Destory();
			UDPServer::Destory();
			AsyncTaskThread::Destory();
			EventPoller::Destory();
			DebugL << "clear common" << endl;
			Logger::Destory();
		});
	},nullptr);
}

API_EXPORT void CALLTYPE onAppExit(){
	cleaner::Destory();
}
API_EXPORT int CALLTYPE initRtspServer(unsigned short port) {
	s_pRtspSrv.reset(new TcpServer<RtspSession>());
	try {
		s_pRtspSrv->start(port);
		return 0;
	} catch (std::exception &ex) {
		s_pRtspSrv.reset();
		WarnL << ex.what();
		return -1;
	}
}


API_EXPORT void CALLTYPE listenEvent_onPlay(onEventPlay cb,void *userData){
	NoticeCenter::Instance().addListener((void *)(cb),Config::Broadcast::kBroadcastRtspSessionPlay,
			[cb,userData](BroadcastRtspSessionPlayArgs){
		static unordered_map<string, void *> s_timerKeyMap;
		static mutex s_mtx;
		uint64_t tag;
		{
			lock_guard<mutex> lck(s_mtx);
			//每个stream随机分配一个内存地址并且不重复
			tag = (uint64_t)&s_timerKeyMap[stream];
		}
		string appTmp(app);
		string streamTmp(stream);
		AsyncTaskThread::Instance().CancelTask(tag);
		int i = 2;
		AsyncTaskThread::Instance().DoTaskDelay(tag,50,[cb,userData,appTmp,streamTmp,i](){
			InfoL << "listenEvent_onPlay:" << appTmp << " " <<  streamTmp << " " << i;
			cb(userData,appTmp.data(),streamTmp.data());
			return (--const_cast<int &>(i)) > 0;
		});
	});
}

API_EXPORT void CALLTYPE listenEvent_onRegistRtsp(onEventRegistMediaSrc cb,void *userData){
	NoticeCenter::Instance().addListener((void *)(cb),Config::Broadcast::kBroadcastRtspSrcRegisted,
			[cb,userData](BroadcastRtspSrcRegistedArgs){
			cb(userData,app,stream);
	});
}



#ifdef __cplusplus
}
#endif
